var cron = require('cron').CronJob;
//todo cron job management

var cronList = [];

var advancedCron =function(config){
    var _self = this;

    this.count = 0;
    this.start = config.start || new Date();
    this.end = config.end || null;
    this.freq = config.freq || "0 0 0 * * *";
    this.monitorFreq = config.monitor || "0 */30 * * * *";

    this.started = false;
    this.timeZone = config.timeZone || 'Asia/Chongqing';
    this.worker = config.worker ||
    function(){ console.log('Cron Pro : no schedule is working, plz check config.') };
    this.scope = config.scope || {};

    this.job = new cron(this.freq,function(){
        _self.worker.apply && _self.worker.call(_self.scope);
    },null,false,this.timeZone);

    this.monitor = new cron(this.monitorFreq,function(){
        if(new Date() >= _self.start){
            if(!_self.started) {
                _self.started = true;
                _self.job.start();
                console.log("Cron Pro : start job cron...");
            }
        }
        if(_self.end && new Date() > _self.end) {
            if(_self.started) {
                _self.started = false;
                _self.job.stop();
                _self.monitor.stop();
                setTimeout(function(){console.log("Cron Pro : stop job cron...")},1000);
            }
        }
    },null,true,this.timeZone);
    console.log("Cron Pro : create new CronTable->[" + this.freq + "]");
    return this;
};

advancedCron.prototype.manualStart = function() {
    this.monitor.stop();
    this.job.start();
    this.started = true;
    console.log("Cron Pro : manually start job cron...");
};

advancedCron.prototype.manualStop = function() {
    if(this.started) {
        this.job.stop();
        console.log("Cron Pro : manually stop job cron...");
    } else {
        console.log("Cron Pro : please start job cron first.");
    }
};

exports.cronProcess = advancedCron;
exports.cronList = cronList;

// todo init(); setup db cronJobs when server setup